package com.poker.util;

import com.alibaba.fastjson.JSONObject;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Map;

/**
 * @Author: yuanZ
 * @Date: 2018/8/16 23:27
 * @Description: Http请求工具类
**/
@Slf4j
public class HttpUtil {

    /**
     * @param: [url: 请求路径, params: 请求参数]
     * @return: com.alibaba.fastjson.JSONObject
     * @Description: Post请求
     */
    @SneakyThrows(IOException.class)
    public static JSONObject post(String url, Map<String, String> params) {
        HttpPost post = getHttpPost(url, params);
        CloseableHttpClient client = HttpClients.createDefault();

        @Cleanup CloseableHttpResponse response = client.execute(post);
        String entity = EntityUtils.toString(response.getEntity(), "UTF-8");

        return JSONObject.parseObject(entity);
    }

    /**
     * @param: [url：请求地址]
     * @return: com.alibaba.fastjson.JSONObject
     * @Description: Get请求
     */
    @SneakyThrows(IOException.class)
    public static JSONObject get(String url) {
        HttpGet get = new HttpGet(url);
        CloseableHttpClient client = HttpClients.createDefault();

        CloseableHttpResponse response = client.execute(get);
        String entity = EntityUtils.toString(response.getEntity(), "UTF-8");

        return JSONObject.parseObject(entity);
    }

    @SneakyThrows({UnsupportedEncodingException.class})
    private static HttpPost getHttpPost(String url, Map<String, String> paramsMap) {
        HttpPost post = new HttpPost(url);

        ArrayList<NameValuePair> paramList = new ArrayList<>();
        for (Map.Entry<String, String> param : paramsMap.entrySet()) {
            NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
            paramList.add(pair);
        }
        post.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));

        return post;
    }

}
